package com.guldan.core.redis;

import com.guldan.core.utils.DateUtil;
import com.guldan.core.utils.SystemUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Silas.
 * Date: 2017/1/18
 * Time: 23:54
 */
public class DistributeLock {

    String key;
    int TIMEOUT = 10 * 1000;   //毫秒数  10秒
    long lock_timeout;
    boolean locked = false;
    CacheService cacheService;

    public DistributeLock() {
    }

    public DistributeLock(String key, CacheService cacheService) {
        this.key = key;
        this.cacheService = cacheService;
    }

    public Boolean lock() {

        if (cacheService.getCache(key) != null) {
            return false;
        }
        cacheService.putCache(key, 1L, 60);
        return true;
    }

    public Boolean lock1() {

        while (!locked) {

            long now = System.currentTimeMillis();
            lock_timeout = now + TIMEOUT + 1000;
            locked = cacheService.putCacheIfAbsent(key, lock_timeout);
            if (locked || (now > (Long) cacheService.getCache(key) && now > (Long) cacheService.getCacheAndSet(key, lock_timeout))) {
                break;
            } else {
                try {
                    Thread.sleep(500L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public void unLock1() {
        try {
            long now = System.currentTimeMillis();
            if (now < lock_timeout)   //只有在超时时间内才能删除，过了超时时间，则认为是
                cacheService.removeCache(key);
        } catch (Exception ex) {

        }
    }

    public void unLock() {
        try {
            cacheService.removeCache(key);
        } catch (Exception ex) {

        }
    }

    public static void main(String args[]) {
        Date d = new Date();
        Date t = DateUtil.add(d, Calendar.DAY_OF_MONTH, 10);
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        System.out.println(df.format(t));
    }
}
